<template>
  <div class="box">
    <el-switch style="display: block" v-model="value" active-color="#13ce66" inactive-color="#13ce66" active-text="时间"
      inactive-text="公里标" @change="change"></el-switch>
    <div class="chart" ref="chartsItem" id="chartsItem"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  props: {
    list: {
      type: Object,
      default () {
        return {};
      }
    },
    videoTime: {
      type: Number,
      default: 0
    },
    progressValue: {
      type: Number,
      default: 0
    },
    startT: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      datasList: [],
      data1: [],
      data2: [],
      data3: [],
      colors: ['#5470C6', '#EE6666', '#ffff00'],
      currentList: [],
      value: true,
      kilometer: [],
      myChart: null,
      pointIcon: 'https://img.alicdn.com/imgextra/i1/2200676927379/O1CN01JvuVeR24NdXxskaNO_!!2200676927379.png',
      currentIndex: 0,
      interval: null,
      currentTime: '',
      // datasIndex: 0
    };
  },
  mounted () {
    this.initializeData();
    this.initializeChart();
    let timestampS = Number(this.getTimestampStr(this.startT)) + this.progressValue
    this.currentTime = this.formatTooltip(this.progressValue)
    this.currentIndex = this.findNextSmallerValue(this.datasList,this.currentIndex,timestampS)
    if(this.currentIndex>0){
      this.startIconMovement()
    }
  },
  methods: {
      strainer(value, type) {
      const dt = new Date(value)
      // 返回年数的四位数方法
      const y = dt.getFullYear()
      // 月份从0开始，所有要加1，如果不足两位用es6字符串方法补0
      const m = (dt.getMonth() + 1 + '').padStart(2, '0')
      const d = (dt.getDate() + '').padStart(2, '0')

      const hh = (dt.getHours() + '').padStart(2, '0')
      const mm = (dt.getMinutes() + '').padStart(2, '0')
      const ss = (dt.getSeconds() + '').padStart(2, '0')
      if(type === 'yyyy-MM-dd'){
      return `${y}-${m}-${d}`
      }else if(type === 'hh:mm'){
      return `${hh}:${mm}`
      }else if(type === 'HH:mm:ss'){
      return `${hh}:${mm}:${ss}`
      }else if(type === 'yyyy年MM月'){
      return `${y}年${m}月`
      }else {
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
      }
    },
    formatTooltip(val) {
      let value = Number(this.getTimestamp(this.startT)) + val
      return this.strainer(value,'HH:mm:ss')
    },
    initializeData () {
      let arr = [];
      let newarr = [];
      Object.keys(this.list).forEach(item => {
        arr.push(this.getTimestamp(item));
      });
      newarr = arr.sort((a, b) => a - b);
      newarr.forEach(item => {
        this.datasList.push(this.timestampToTime(item));
        this.currentList.push(this.timestampToTime2(item));
      });
      // console.log('this.this.currentList.splice(0,10)',this.datasList.splice(this.currentIndex,10))
      
      Object.values(this.list).forEach(item => {
        this.kilometer.push(item.encode22);
        this.data1.push(item.encode16);
        this.data2.push(item.encode26);
        this.data3.push('120');
      });
    },
    getTimestamp (val) {
      return Math.floor(new Date(val).getTime() / 1000);
    },
    getTimestampStr(val){
      var timeString = val; // 时分秒字符串
      var currentDate = new Date(); // 当前日期对象
      var dateString = currentDate.toDateString(); // 获取当前日期的字符串表示（不包含时分秒）
      var dateTimeString = dateString + ' ' + timeString; // 拼接日期和时分秒字符串
      var timestamp = Date.parse(dateTimeString); // 将日期时间字符串转换为时间戳
      return timestamp
    },
    getTimestampSencond(val){
      var timeString = val; // 时分秒字符串
      var currentDate = new Date(); // 当前日期对象
      var dateString = currentDate.toDateString(); // 获取当前日期的字符串表示（不包含时分秒）
      var dateTimeString = dateString + ' ' + timeString; // 拼接日期和时分秒字符串
      var timestamp = Date.parse(dateTimeString); // 将日期时间字符串转换为时间戳
      return timestamp
    },
    timestampToTime (timestamp) {
      var date = new Date(timestamp * 1000);
      var h = date.getHours() + ":";
      var m = date.getMinutes() + ":";
      var s = date.getSeconds();
      return h + m + s;
    },
    timestampToTime2 (timestamp) {
      var date = new Date(timestamp * 1000);
      var Y = date.getFullYear() + "-";
      var M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
      var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h = date.getHours() + ":";
      var m = date.getMinutes() + ":";
      var s = date.getSeconds();
      return Y + M + D + h + m + s;
    },
    initializeChart () {
      const chartDom = this.$refs.chartsItem;
      this.myChart = echarts.init(chartDom);

      const option = {
        color: this.colors,
        tooltip: {
          trigger: 'none',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          textStyle: {
              color: '#ffffff' // 这里设置图例的字体颜色为红色
          }
        },
        grid: {
          top: 70,
          bottom: 50
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.datasList.splice(this.currentIndex,10)
        },
        yAxis: [
          {
            name: '管压KPA',
            type: 'value'
          },
          {
            name: '速度km/h',
            nameLocation: 'start',
            alignTicks: true,
            type: 'category',
            inverse: true,
            data: [150, 120, 90, 60, 30, 0]
          }
        ],
        series: [
          {
            name: '速度km/h',
            type: 'line',
            smooth: true,
            emphasis: {
              focus: 'series'
            },
            data: this.data1.reverse()
          },
          {
            name: '管压力KPA',
            type: 'line',
            smooth: true,
            emphasis: {
              focus: 'series'
            },
            data: this.data2.reverse()
          },
          {
            name: '限速',
            type: 'line',
            smooth: true,
            emphasis: {
              focus: 'series'
            },
            data: this.data3
          }
        ],
        graphic: [
          {
            type: 'image',
            id: 'movingIcon',
            left: '9%', // Initial value
            top: '49%',
            z: 100,
            bounding: 'raw',
            style: {
              image: this.pointIcon,
              width: 40,
              height: 40
            }
          }
        ]
      };

      this.myChart.setOption(option);
      this.currentIndex = 0;
      this.startIconMovement();

      this.myChart.on('click', params => {
        const times = this.currentList[this.currentList.length - 1];
        this.$emit('clickIdxChart', times);
        this.$emit('clickIdxChartChange', params.name);
      });
    },
    startIconMovement () {
      // this.interval = setInterval(() => {
        console.log('startIconMovement.currentIndex:',this.currentIndex)
        console.log('xAxis',this.datasList[this.currentIndex])
        if (this.currentIndex < this.datasList.length) {
          // let arr = this.datasList.splice(this.currentIndex,10)
          const xPixel = this.myChart.convertToPixel('xAxis', this.datasList[this.currentIndex]);
          // const xPixel = this.myChart.convertToPixel('xAxis', '11:5:48')
          console.log('xPixel',xPixel)
          const chartWidth = this.myChart.getWidth();
          const leftPercentage = (xPixel / chartWidth) * 100;
          console.log('getHeight:',leftPercentage)
          this.myChart.setOption({
            color: this.colors,
            tooltip: {
              trigger: 'none',
              axisPointer: {
                type: 'cross'
              }
            },
            legend: {
              textStyle: {
                  color: '#ffffff' // 这里设置图例的字体颜色为白色
              }
            },
            grid: {
              top: 70,
              bottom: 50
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: this.datasList.slice(this.currentIndex,10)
            },
            yAxis: [
              {
                name: '管压KPA',
                type: 'value'
              },
              {
                name: '速度km/h',
                nameLocation: 'start',
                alignTicks: true,
                type: 'category',
                inverse: true,
                data: [150, 120, 90, 60, 30, 0]
              }
            ],
            series: [
              {
                name: '速度km/h',
                type: 'line',
                smooth: true,
                emphasis: {
                  focus: 'series'
                },
                data: this.data1.reverse()
              },
              {
                name: '管压力KPA',
                type: 'line',
                smooth: true,
                emphasis: {
                  focus: 'series'
                },
                data: this.data2.reverse()
              },
              {
                name: '限速',
                type: 'line',
                smooth: true,
                emphasis: {
                  focus: 'series'
                },
                data: this.data3
              }
            ],
            graphic: [
              {
                id: 'movingIcon',
                type: 'image', // Ensure 'type' is set
                style: {
                  image: this.pointIcon,
                  width: 40,
                  height: 40,
                  x: xPixel + 0, // Adjust x position to center icon
                  y: this.myChart.getHeight() * 0.6 - 20 // Adjust y position to center icon
                },
                // position: [myChart.convertToPixel({ xAxisId: 'x0' }, result['L1'] < result['L2'] ? result['L1'] : result['L2']) + 5, 0],
              }
            ]
          }, true); // Force update to refresh the graphic
        } else {
          // 请求接口
          // console.log('999',this.datasList,this.datasList[this.datasList.length-1])
          let times = this.currentList[this.currentList.length-1]
          this.$emit('clickIdxChart', times);
        }
        //  else {
        //   clearInterval(this.interval);
        // }
      // }, 2000);
    },
    change (e) {
      this.value = e;
      const option = {
        xAxis: {
          data: this.value ? this.datasList : this.kilometer
        }
      };
      this.myChart.setOption(option);
    },
    findNextSmallerValue(arr, currentIndex,timestampS) {
      if (currentIndex === arr.length - 1) {
        return null; // 当前元素已是数组的最后一个，没有下一个更大的值
      }
      for (let i = 0; i < arr.length; i++) {
        // console.log('this.getTimestampStr(arr[i)',this.getTimestampStr(arr[i]),timestampS,this.getTimestampStr(arr[i+1]),this.getTimestampStr(arr[i])<timestampS,timestampS<=this.getTimestampStr(arr[i+1]))
        if (this.getTimestampStr(arr[i])<timestampS&&timestampS<=this.getTimestampStr(arr[i+1])) {
          return i+1; // 找到下一个更小的值
        }
      }
      return 0; // 没有找到更小的值
    }
  },
  watch:{
    'progressValue':{
      handler(newV,OldV){
        let timestampS = Number(this.getTimestampStr(this.startT)) + newV
        // console.log('timestampS',this.strainer(timestampS,'HH:mm:ss'),this.datasList,this.currentIndex,this.datasList[this.currentIndex])
        if(newV&&newV!=OldV){
          let i = this.findNextSmallerValue(this.datasList,this.currentIndex,timestampS)
         if(this.currentIndex<i){
            this.currentIndex ++;
            this.startIconMovement()
          }
        }
      },
      deep:true
    }
  }
};
</script>

<style scoped>
.box {
  height: 100%;
}

.chart {
  height: 100%;
}
</style>
